<template>
  <el-dialog
    v-model="dialogVisible"
    title="选择气测人员"
    width="600px"
    @close="handleClose"
  >
    <div class="detector-select">
      <!-- 筛选条件 -->
      <div class="filter-section">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-select v-model="filters.department" placeholder="选择部门" @change="handleFilter">
              <el-option label="全部" value="" />
              <el-option label="维修部" value="maintenance" />
              <el-option label="生产部" value="production" />
              <el-option label="安全部" value="safety" />
            </el-select>
          </el-col>
          <el-col :span="12">
            <el-input
              v-model="filters.keyword"
              placeholder="搜索姓名或工号"
              @input="handleFilter"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
        </el-row>
      </div>
      
      <!-- 气测人员列表 -->
      <div class="detector-list">
        <el-table
          :data="filteredDetectors"
          @selection-change="handleSelectionChange"
          max-height="300"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="name" label="姓名" width="100" />
          <el-table-column prop="employeeId" label="工号" width="100" />
          <el-table-column prop="department" label="部门" width="120" />
          <el-table-column prop="role" label="角色" width="100">
            <template #default="{ row }">
              <el-tag size="small">{{ getRoleLabel(row.role) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="certificateNumber" label="证书编号" width="150" />
          <el-table-column prop="certificateExpiry" label="证书有效期" width="120">
            <template #default="{ row }">
              <span :class="{ 'expired': isExpired(row.certificateExpiry) }">
                {{ row.certificateExpiry }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="row.status === 'available' ? 'success' : 'danger'" size="small">
                {{ row.status === 'available' ? '可用' : '不可用' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 已选择人员 -->
      <div v-if="selectedDetectors.length > 0" class="selected-section">
        <h4>已选择气测人员 ({{ selectedDetectors.length }})</h4>
        <div class="selected-list">
          <el-tag
            v-for="detector in selectedDetectors"
            :key="detector.id"
            closable
            @close="removeSelected(detector.id)"
            style="margin-right: 8px; margin-bottom: 8px"
          >
            {{ detector.name }} ({{ getRoleLabel(detector.role) }})
          </el-tag>
        </div>
      </div>
    </div>
    
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleConfirm" :disabled="selectedDetectors.length === 0">
        确定 ({{ selectedDetectors.length }})
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'

interface GasDetector {
  id: string
  name: string
  employeeId: string
  department: string
  role: string
  certificateNumber: string
  certificateExpiry: string
  status: 'available' | 'unavailable'
}

interface Props {
  modelValue: boolean
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'confirm', detectors: GasDetector[]): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const filters = reactive({
  department: '',
  keyword: ''
})

const selectedDetectors = ref<GasDetector[]>([])

// 模拟气测人员数据
const detectorData: GasDetector[] = [
  {
    id: '1',
    name: '孙八',
    employeeId: 'G001',
    department: '安全部',
    role: 'gas_detector',
    certificateNumber: 'GD2023001',
    certificateExpiry: '2025-12-31',
    status: 'available'
  },
  {
    id: '2',
    name: '周九',
    employeeId: 'G002',
    department: '安全部',
    role: 'gas_detector',
    certificateNumber: 'GD2023002',
    certificateExpiry: '2025-10-15',
    status: 'available'
  },
  {
    id: '3',
    name: '吴十',
    employeeId: 'G003',
    department: '维修部',
    role: 'safety_officer',
    certificateNumber: 'SO2023001',
    certificateExpiry: '2023-12-31',
    status: 'unavailable'
  },
  {
    id: '4',
    name: '郑十一',
    employeeId: 'G004',
    department: '生产部',
    role: 'gas_detector',
    certificateNumber: 'GD2023003',
    certificateExpiry: '2025-08-20',
    status: 'available'
  }
]

// 过滤后的气测人员列表
const filteredDetectors = computed(() => {
  let result = detectorData

  // 根据筛选条件过滤
  if (filters.department) {
    result = result.filter(detector => detector.department === filters.department)
  }

  if (filters.keyword) {
    const keyword = filters.keyword.toLowerCase()
    result = result.filter(detector => 
      detector.name.toLowerCase().includes(keyword) ||
      detector.employeeId.toLowerCase().includes(keyword)
    )
  }

  return result
})

// 获取角色标签
const getRoleLabel = (role: string) => {
  const roleMap: Record<string, string> = {
    gas_detector: '气测员',
    safety_officer: '安全员'
  }
  return roleMap[role] || role
}

// 检查证书是否过期
const isExpired = (expiryDate: string) => {
  const today = new Date()
  const expiry = new Date(expiryDate)
  return expiry < today
}

// 处理筛选
const handleFilter = () => {
  // 筛选逻辑已在计算属性中处理
}

// 处理选择变化
const handleSelectionChange = (selection: GasDetector[]) => {
  selectedDetectors.value = selection
}

// 移除已选择的人员
const removeSelected = (id: string) => {
  selectedDetectors.value = selectedDetectors.value.filter(detector => detector.id !== id)
}

// 确认选择
const handleConfirm = () => {
  if (selectedDetectors.value.length === 0) {
    ElMessage.warning('请至少选择一名气测人员')
    return
  }

  // 检查是否有证书过期的人员
  const expiredDetectors = selectedDetectors.value.filter(detector => 
    isExpired(detector.certificateExpiry)
  )

  if (expiredDetectors.length > 0) {
    ElMessage.warning('所选人员中有证书已过期，请重新选择')
    return
  }

  emit('confirm', selectedDetectors.value)
  handleClose()
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  selectedDetectors.value = []
  filters.department = ''
  filters.keyword = ''
}

// 监听对话框显示状态
watch(dialogVisible, (visible) => {
  if (visible) {
    selectedDetectors.value = []
  }
})
</script>

<style lang="scss" scoped>
.detector-select {
  .filter-section {
    margin-bottom: 20px;
    padding: 16px;
    background: #f8f9fa;
    border-radius: 4px;
  }
  
  .detector-list {
    margin-bottom: 20px;
    
    .expired {
      color: #f56c6c;
      font-weight: 500;
    }
  }
  
  .selected-section {
    h4 {
      color: #333;
      margin-bottom: 12px;
    }
    
    .selected-list {
      min-height: 40px;
      padding: 12px;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      background: #f8f9fa;
    }
  }
}
</style>

